package com.hzchendou.blog.demo.auth.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Date: 2022-06-01 11:10
 * @since: 1.0
 */
@Service
public class AuthUserDetailService implements UserDetailsService {

    Map<String, User> users = new HashMap<>();

    @PostConstruct
    public void init() {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        User admin = new User("admin", passwordEncoder.encode("admin"), AuthorityUtils.createAuthorityList("admin"));
        User user = new User("user", passwordEncoder.encode("user"), AuthorityUtils.createAuthorityList("user"));
        users.put("admin", admin);
        users.put("user", user);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (users.containsKey(username)) {
            User user = users.get(username);
            return new User(user.getUsername(), user.getPassword(), new ArrayList<>(user.getAuthorities()));
        }
        throw new UsernameNotFoundException("用户信息不存在");
    }
}
